package driving;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.g2room.driving.generate.to.ArticleTo;
import com.g2room.driving.util.DbUtil;
import com.g2room.driving.util.ImageUtil;
/**
 * 处理未使用的图片信息
 * @author Administrator
 *
 */
public class DelNoUseImg {
	public static void main(String[] args) {
		// 获取 数据库所有图片链接
		List<String> dbImgUrl = getArtisImgs();
		
		// 遍历文件夹，获取所有的图片，只对比年月日后面的
		Map<String, String> imgs = getFiles();
		for(String img : imgs.keySet()) {
			if(dbImgUrl.contains(img)) continue;
			// 移动到另外一个目录，并删除
			File f = new File(imgs.get(img));
			if (f.renameTo(new File("E:/高绪国/资料/html/kaichejiqiao/imgs/backup/" + f.getName()))) {
				System.out.println("File is moved successful!" + f.getName());
			}
		}
	}
	
	public static Map<String, String> getFiles() {
		Map<String, String> imgFiles = new HashMap<String, String>();
		imgFiles.put("E:/高绪国/资料/html/kaichejiqiao/imgs/20160420", "http://www.wine22.com/20160420/");
		imgFiles.put("E:/高绪国/资料/html/kaichejiqiao/imgs/20160417", "http://www.g2room.com/20160417/");
		imgFiles.put("E:/高绪国/资料/html/kaichejiqiao/imgs/20160418", "http://www.g2room.com/20160418/");

		Map<String, String> imgs = new HashMap<String, String>();
		for(String img : imgFiles.keySet()) {
			File f = new File(img);
			String[] dirs = f.list();
			for(String dir : dirs) {
				File file =new File(img + "/" + dir);
				for(String imgName : file.list()) {
					System.out.println(imgName);
					imgs.put(imgFiles.get(img) + dir + "/" + imgName, img + "/" + dir + "/" + imgName);
				}
			}
			
		}
		return imgs;
	}
	
	public static List<String> getArtisImgs() {
		List<String> imgs = new ArrayList<String>();
		String sql = "select id,content from d_article_grap";
		try {
			Connection connection = DbUtil.getConn();
			Statement statement = connection.createStatement();
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				ArticleTo articleTo = new ArticleTo();
				articleTo.setId(rs.getLong("id"));
				String content = rs.getString("content");
				List<String> imgSrcs = ImageUtil.getImgSrc(content);
				for(String imgSrc : imgSrcs) {
					imgSrc = imgSrc.replaceAll("http://www.g2room.com/images/", "")
							.replaceAll("http://www.wine22.com/images/", "");
					imgs.add(imgSrc);
					
				}
			}
			rs.close();
			statement.close();
		} catch (Exception e) {
			System.out.println("获取数据发生异常：" + e.getMessage());
			e.printStackTrace();
		}
		return imgs;
	}
}
